import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:interrogation/src/data/api.dart';
import 'package:interrogation/src/data/models/get_info_res.dart';
import 'package:interrogation/src/data/models/login_res.dart';


import '../../../../../app/routes/app_pages.dart';
import '../../../../base/utils/logger.dart';
import '../../../../base/utils/storage_manager.dart';
import '../../../../main_service.dart';

class LoginController extends GetxController {
  //TODO: Implement LoginController

  final count = 0.obs;

  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;

  login() async {
    Get.offAndToNamed(Routes.HOME_INDEX);
    LoginRes? res = await Api.login(
        username: accountController.text, password: passwordController.text);

    if (res != null) {
      BrnToast.show("登录成功", Get.context as BuildContext);
      StorageManager.putString(StorageConst.token, res.data?.accessToken ?? '');
      Get.find<MainService>().userId = res.data?.userId ?? 0;
      await getUserInfo();
      Get.offAndToNamed(Routes.HOME_INDEX);
    }
  }

  getUserInfo()async{
    try {
      UserInfo? userInfo = await Api.getUserInfo();
      if (userInfo != null) {
        Get.find<MainService>().userInfo = userInfo!;
      }
    } catch (e) {
      loggy.error(e);
    }
  }
}
